<?php

namespace app\modules\log\service;

use Yii;
use app\common\base\CommonService;
use app\helpers\DatetimeHelper;
use app\modules\log\models\DeviceLogs;
use ValueError;

class DeviceLogsService extends CommonService
{
    function __construct()
    {
        // 对父类service(component)初始化，并指定model
        parent::init();
        $this->model = new DeviceLogs();
    }

    /**
     * 记录操作
     * @param integer $userId 操作人的userId
     * @param integer $operationId 操作功能
     * @param integer $deviceId 被操作的机器Id
     * @param integer $old 原始数据
     * @param integer $new 修改后的数据
     */
    public function record($userId, $operationId, $deviceId, $old, $new)
    {
        $this->model->userId = $userId;
        $this->model->operationId = $operationId;
        $this->model->deviceId = $deviceId;
        $this->model->timestamp = DatetimeHelper::msectime();
        $operation = parent::callModuleService('log', 'OperationService', 'findName', $operationId);
        $userName = parent::callModuleService('user', 'AccountService', 'idToUsername', $userId);
        $this->model->message = "User " . $userName . "(userid: " . $userId . ")" . " use " . $operation . " to change the data of " . $deviceId . "(deviceid)" . " from " . $old . " to " . $new . " at " . date('Y-m-d H:i:s');
        $this->model->save();
        return $this->model->message;
    }
    /**
     * 记录查询
     * @param integer $userId 操作人的userId
     * @param integer $operationId 操作功能
     * @param integer $deviceId 被操作的机器Id
     * @param string $timeStart 起始时间
     * @param string $timeEnd 结束时间
     * @return array $info 所有符合条件的结果
     */
    public function find($userId, $operationId, $deviceId, $timeStart, $timeEnd)
    {
        $start = DatetimeHelper::formatToMSecTimeStamp($timeStart);
        $end = DatetimeHelper::formatToMSecTimeStamp($timeEnd);
        $lists = $this->lists([
            'condition' => ['and', 'userId' => $userId, 'operationId' => $operationId, 'deviceId' => $deviceId, ['between', 'timestamp', $start, $end]],
            'orderby' => 'id',
        ]);
        if (empty($lists)) return parent::error('ERROR_INVALID_CONDITION', '查询记录不存在');
        return [
            'info' => $lists,
        ];
    }
}
